# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 13:33:06 2018

@author: Who

链通财经
http://www.liantongcj.com/

"""
import requests
import re
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url, data):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.post(url, timeout=30, data=data, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_Zx(url, data):
    text = get_html_text(url, data)
    if not text:
        return None
    regex = re.compile(r"<span class='mixNewsStyleDate fk-newsListDate'>([\s\S]*?)<")
    dates = re.findall(regex, text)
    return dates


def count_process_one():  # 快讯
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        data = {
            'cmd': 'getAjaxPageModuleInfo',
            '_colId': '107',
            '_extId': '0',
            'moduleId': '700',
            'href': '/h-col-107.html?m700pageno={}#fai_700_top'.format(a)
        }
        url = 'http://www.liantongcj.com/ajax/ajaxLoadModuleDom_h.jsp'
        dates = get_dates_Zx(url, data)
        if not dates:
            break
        print('---- 链通财经资讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '链通财经'
    t1 = count_process_one()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0], "yesterday": t1[1], "frontday": t1[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
